<template>
  <eui-background type="common">
    <eui-navbar ref="EuiNavBar" :title="title" displayable="true" />
    <view class="top-view" @click="openPopupMain">
      <eui-card title="查询条件" hPadding="28">
        <template v-slot:extra>
          <view v-if="Conditions.length > 0" class="extra-view">
            <eui-uicons type="right" size="32" />
          </view>
        </template>
        <view class="item-view">
          <eui-text v-for="condition in Conditions.filter(cond => cond.ParamValue)" :key="condition.mTitle" type="name2"
            :title="condition.mTitle" :value="condition.ParamValue" cWidth="width: 100%" :valueStyle="valueStyle" />
        </view>
      </eui-card>
    </view>
    <view class="main-view" :style="{ height: listHeight + 'rpx' }">
      <eui-paging ref="paging" v-model="listManager" :fixed="false" :refresher-enabled="false"
                  :default-page-size="10" :loading-more-enabled="true" :show-loading-more-when-reload="false">
        <view class="item-view list-view" v-for="(scope, index) in listManager" :key="index"
              @click="onClickGoToDetail(index)">
          <view class="list-index-view">
            <text>{{ index + 1 }}</text>
          </view>
          <eui-text v-for="(item, itemIndex) in scope" :key="itemIndex" :type="item.Type"
                    :precision="item.Precision" :title="ColumnMetas[itemIndex]?.Title" :value="item.Value"
                    :valueStyle="valueStyle + item.AlignType" />
        </view>
      </eui-paging>
    </view>
    <eui-popup ref="gdsPopup" background-color="#f8f8f8" type="bottom" :mask-click="true">
      <view class="popup-title">
        <text>查询条件</text>
      </view>
      <view class="popup-content">
        <scroll-view scroll-y="true" :style="{ height: '500rpx', overflow: 'visible', position: 'relative' }">
          <eui-card-input v-for="(condition, index) in tempConditions" :key="index" :ref="condition.ParamRef"
                          align-type="left" placement="top" :required="condition.IsRequired"
                          v-model="condition.ParamValue" :title="condition.mTitle" :type="condition.ParamType"
                          titleWidth=225 @input="judgeInput(condition)"
                          :rightIconType="['text', 'number'].includes(condition.ParamType) ? 'clear' : 'right'"
                          :range="condition.ParamRange" :displayable="false" :placeholder="condition.ParamPlaceholder"
                          @iconClick="clickRight(condition, index)" />
        </scroll-view>
        <view class="popup-bottom">
          <eui-button type="max2" title="取消" singleTag="cancel" @buttonClick="confirm"></eui-button>
          <eui-button type="max" title="查询" singleTag="search" @buttonClick="confirm"></eui-button>
        </view>
      </view>
    </eui-popup>
    <eui-popup ref="goodsInfo" background-color="#f8f8f8" type="bottom" :style="{ maxHeight: '80vh' }" :mask-click="true">
      <view class="popup-title">
        <text>商品详情</text>
      </view>
      <view class="scroll-popup-content">
        <scroll-view scroll-y="true" class="scroll-style">
          <view class="scroll-item-view">
            <view v-for="(item, itemIndex) in curGoodsInfo" :key="itemIndex" class="detail-view"
                  :class="itemIndex % 2 === 0 ? 'white-view':'gray-view'">
              <eui-text :type="item.Type"
                        :precision="item.Precision" :title="ColumnMetas[itemIndex]?.Title" :value="item.Value"
                        :valueStyle="item.AlignType" cWidth="width: 65%" />
            </view>
          </view>
        </scroll-view>
      </view>
    </eui-popup>
  </eui-background>
</template>

<script setup type="ts">
import { onMounted, ref, reactive, computed } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { validateStores, validateGds, defaultMapping, validateStoresAndWno } from '@/hooks/useValidateMethod';
import { todayAdd, formatNow } from '@/hooks/useUtils';
import service from "@/common/service";
import { rdsRequest, getRdsUrl } from '@/hooks/rdsServices';
import { calcAtInByPt, validateOddLot, round, calcPtInByPtPay, calcPetpayByPtPay } from '@/hooks/useCalculateMethod';
import { useMainStore } from "@/store/modules/store";
import { useLoginStore } from "@/store/modules/useLoginStore";
import { init, getRdsUserDepartAuthority, getRdsSysConfig } from '@/hooks/init';
import dateRangUtil from "@/common/dateRangUtil";
import { validateAdnoLevel } from '@/hooks/useBillInfo';
import Enjoy from "@/common/enjoy";
import { getDcStoreInfo } from '@/hooks/useDcStoreInfo';
import {
  cutPrefix,
  DefaultValueOptionArray,
  convertValue,
  isOption,
  getType,
  getRef,
  getRange,
  getTitle,
  getPlaceholder,
  getNewValue,
  getHeadValue,
  getAlignType,
} from "../Hooks/useDefaultValue.js";

const rdsUrl = getRdsUrl();
// 明细样式
const valueStyle = ref('white-space: nowrap;overflow: hidden;text-overflow: ellipsis;')
const showRightStyle = ref('text-align: right');
const showRedStyle = ref('text-align: right;color: #FF4000;');
const isOpened = ref('none');
const mainStore = useMainStore();
const LoginStore = useLoginStore();
const listHeight = ref(300);
const oriHeight = ref(300);
// 标题
const title = ref('');
// 进入界面时传入的参数
const option = ref({
  c_mdcode: '',
  c_mdtitle: '',
});
// 展示的数据结构
const listManager = ref([]);
const reportData = ref([]);
const totalInfo = ref({});
// 列名
const AdvanceColumns = ref([]);
// 列元信息
const ColumnMetas = ref([]);
// 查询条件
const Conditions = ref([]);
const gdsPopup = ref(null);
const goodsInfo = ref(null);
const paging = ref(null);
// 临时数据
const tempConditions = ref([]);
// 当前商品
const curGoodsInfo = ref({});
const { loginInfo } = mainStore;
// 当前method
const currentMethod = ref('');

const isUrlEncoded = (str) => {
  // 正则表达式：匹配以 % 开头，后面跟着两个十六进制数字的模式
  return /%[0-9A-Fa-f]{2}/.test(str);
}

const safeDecodeURIComponent = (encodedStr) => {
  if (isUrlEncoded(encodedStr)) {
    try {
      return decodeURIComponent(encodedStr);
    } catch (e) {
      return '';
    }
  } else {
    // 如果不是 URL 编码字符串，直接返回原值
    return encodedStr;
  }
}

onLoad(async (option) => {
  await parseOption(option);
  if (!option.c_mdcode || option.c_mdcode.length === 0) {
    return;
  }
  title.value = safeDecodeURIComponent(option.c_mdtitle);
  await getRdsReportField();
})

const showList = computed(() => {
  return reportData.value;
});

const parseOption = async (op) => {
  if (op) {
    option.value.c_mdcode = op.c_mdcode;
    option.value.c_mdtitle = safeDecodeURIComponent(op.c_mdtitle);
    return;
  }
  service.enjoyShowLoading('获取界面编码失败');
  setTimeout(() => {
    service.enjoyHideLoading();
  }, 2000);
}

// 调用rds接口获取当前模块的字段
const getRdsReportField = async () => {
  service.enjoyShowLoading('正在加载...');
  // 获取字段信息
  const reportInfo = await rdsRequest(rdsUrl.reportApi, 'reportview', 'FetchReportFormat', option.value.c_mdcode);
  AdvanceColumns.value = reportInfo.AdvanceColumns;
  Conditions.value = reportInfo.Conditions;
  ColumnMetas.value = reportInfo.ColumnMetas;

  if (!Conditions.value || Conditions.value.length === 0) {
    service.enjoyHideLoading();
    return;
  }

  // 获取字段的默认值
  for (let i = 0; i < Conditions.value.length; i++) {
    let defaultValue = Conditions.value[i].DefaultValue;
    let inputMethod = Conditions.value[i].InputMethod;
    Conditions.value[i].ParamValue = await switchDefaultValue(defaultValue, inputMethod);
    Conditions.value[i].ParamType = getType(Conditions.value[i]);
    Conditions.value[i].ParamRef = getRef(Conditions.value[i]);
    Conditions.value[i].ParamRange = getRange(Conditions.value[i]);
    Conditions.value[i].mTitle = getTitle(Conditions.value[i]);
    Conditions.value[i].ParamPlaceholder = getPlaceholder(Conditions.value[i]);
  }
  service.enjoyHideLoading();
  setTimeout(() => {
    openPopupMain();
    getListHeight();
  }, 300)
}

// 获取列表高度
const getListHeight = async () => {
  await uni.getSystemInfo({
    success: function (res) { // res - 各种参数
      let info = uni.createSelectorQuery().select(".main-view");
      info.boundingClientRect(function (data) { //data - 各种参数
        //获取列表高度
        let height = res.windowHeight - data.top;
        //转换rpx
        let finalHeight = height / (res.windowWidth / 750) - 20;
        listHeight.value = finalHeight;
        oriHeight.value = finalHeight;
      }).exec()
    }
  });
};

const switchDefaultValue = async (defaultValue, inputMethod) => {
  if (inputMethod === '维度列') {
    // 维度暂时处理成单选
    return ''
  }
  if (!isOption(defaultValue)) {
    return defaultValue;
  }
  const cutOption = cutPrefix(defaultValue);
  if (DefaultValueOptionArray.includes(cutOption.prefix)) {
    return convertValue(defaultValue);
  }
  const conditionData = {
    ParamName: defaultValue,
    RptGuid: option.value.c_mdcode,
  };
  return await rdsRequest(rdsUrl.reportApi, 'reportview', 'FetchItemDefaultValue', conditionData);
}

// 数据查询
const searchReportData = async () => {
  service.enjoyShowLoading('正在加载...');
  const { loginInfo } = mainStore;
  // 把@去掉，否则报表服务报错
  Conditions.value.forEach(condition => {
    if (condition && condition.ParamName) {
      condition.ParamName = condition.ParamName.replace('@', '');
    }
  });
  const conditionData = {
    RptGuid: option.value.c_mdcode,
    Userno: loginInfo.sUser,
    WhereDatas: Conditions.value,
    AdvanceWhereData: [],
  };
  const rptDataView = await rdsRequest(rdsUrl.reportApi, 'reportview', 'FetchRptDataView', conditionData);
  if (!rptDataView || !rptDataView.RptData) {
    // 查不到数据就清空数据，报错不管
    uni.showToast({
      title: '暂无数据',
      icon: 'none',
      duration: 2000,
    });
    reportData.value = [];
    listManager.value = [];
    totalInfo.value = {};
    paging.value.setLocalPaging([]);
    service.enjoyHideLoading();
    return;
  }
  const rptData = rptDataView.RptData[0];
  // 组装自己需要的数据
  totalInfo.value = rptData.Total;
  reportData.value = rptData.Data.map(data => {
    // 以当前的ColumnMetas顺序解析数据，避免乱序
    return ColumnMetas.value.map(meta => {
      return {
        Width: meta.Width,
        Value: getNewValue(data, meta),
        AlignType: getAlignType(data, meta),
        Type: 'name2',
        Precision: 2,
      };
    })
  });
  let showList = reportData.value;
  paging.value.setLocalPaging(showList);
  service.enjoyHideLoading();
}

const openPopupMain = () => {
  tempConditions.value = JSON.parse(JSON.stringify(Conditions.value));
  gdsPopup.value.open();
}

const onClickGoToDetail = (index) => {
  curGoodsInfo.value = reportData.value[index];
  goodsInfo.value.open();
}

const judgeInput = (e) => {
}

const confirm = (t) => {
  let { singleTag } = t;
  switch (singleTag) {
    case 'cancel':
      gdsPopup.value.close();
      break;
    case 'search':
      //判断必填项是否有值
      for (let field of tempConditions.value) {
        let { IsRequired, ParamValue, Title } = field;
        // 检查是否是必填项且值为空
        if (IsRequired && (!ParamValue || ParamValue.trim() === "")) {
          uni.showToast({
            title: `[${Title}] 是必填项`,
            icon: 'none',
            duration: 3500,
          });
          return;
        }
      }
      //判断返回行数
      let limitData = tempConditions.value.find(x => x.Name === 'LimitRow');
      if (limitData) {
        let { ParamValue, LimitRow, Title } = limitData;
        let curNum = parseFloat(ParamValue);
        if (curNum < 1 || curNum > LimitRow) {
          uni.showToast({
            title: `[${Title}]必须在 1 和 ${LimitRow} 之间`,
            icon: 'none',
            duration: 3500,
          });
          return;
        }
      }
      //判断时间
      Conditions.value = tempConditions.value;
      searchReportData();
      gdsPopup.value.close();
      break;
  }
}

// 选择框点击事件
const clickRight = (condition, index) => {
  let { InputMethod, ParamType } = condition;
  let parms = Enjoy.GetDialogParms();
  parms.CallBack = SelectionChanged;
  currentMethod.value = InputMethod;
  let IsMult = '是';  //默认多选
  if (InputMethod.includes('store')) {
    let tData = Conditions.value.find(x => x.InputMethod === 'store-limit');
    parms.SelectionType = "机构选择";
    // parms.SelectedItems = tData.ParamValue;
    parms.IsMult = IsMult;
    parms.IsNotPage = true;
    Enjoy.OpenDialog(parms)
  } else if (InputMethod.includes('depart')) { //部门
    uni.navigateTo({
      url: '../../RdsViews/modals/index?type=depart&IsMult=' + IsMult
    });
  } else if (InputMethod.includes('rds_gdsclass')) { //品类
    uni.navigateTo({
      url: '../../RdsViews/modals/index?type=gdsClass&IsMult=' + IsMult
    });
  } else if (InputMethod.includes('rds_brand')) { //品牌
    uni.navigateTo({
      url: '../../RdsViews/modals/index?type=brand&IsMult=' + IsMult
    });
  } else if (InputMethod.includes('rds_partner')) { //供应商
    uni.navigateTo({
      url: '../../RdsViews/modals/index?type=partner&IsMult=' + IsMult
    });
  } else if (ParamType === 'text' || ParamType === 'number') {
    condition.ParamValue = '';
    tempConditions.value[index] = condition;
  }
}

const SelectionChanged = async (type, item) => {
  let targetStr = currentMethod.value;
  for (let i = 0; i < tempConditions.value.length; i++) {
    if (tempConditions.value[i].InputMethod === targetStr) {
      if (type && type.SelectionType) {
        tempConditions.value[i].ParamValue = type.BackParms.Key;
      } else {
        // 多选和单选的取值不同
        // 多选: item.list.join(',');
        // 单选: item.value;
        tempConditions.value[i].ParamValue = item.list.join(',');
      }
      break;
    }
  }
}

defineExpose({
  SelectionChanged
})

</script>

<style lang="scss" scoped>
@import '../../../main.scss';

.top-view {
  width: 100%;
  margin-bottom: 20rpx;
}

.main-view {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.extra-view {
  //position: absolute;
  //right: 30rpx;
}

.footer-view {
  width: 100%;
  flex: 1;
}

.list-scroll {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}

.bottom-view {
  width: 100%;
  height: 100rpx;
  background: #FFFFFF;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  flex-direction: row;
}

.center-style {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  margin-right: 20rpx;
  //gap: 20rpx;
}

.gap-view {
  width: 20rpx;
  height: auto;
}

//内容行
.item-view {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  align-items: center;
  margin-top: 16rpx;
  row-gap: 8rpx;
  position: relative;
}

//内容行
.list-view {
  background: #ffffff;
  padding: 12rpx;
}

.line-view {
  width: 100%;
  height: 1rpx;
  background: #EEEEEE;
  margin: 20rpx 0;
}

.popup-title {
  width: 100%;
  height: 84rpx;
  background: #FFFFFF;
  border-radius: 40rpx 40rpx 0 0;
  display: flex;
  justify-content: center;
  align-items: center;
  color: $uni-text-color-secondary;
  font-size: $uni-font-size-level1;
  line-height: 45rpx;
  text-align: center;
  position: relative;
}

.popup-content {
  position: relative;
  align-items: center;
  justify-content: left;
  flex-direction: column;
  padding: 0;
  width: 100%;
  height: 600rpx;
  background-color: #ffffff;
  z-index: 20;
  overflow: visible;
}

.scroll-popup-content {
  position: relative;
  align-items: center;
  justify-content: left;
  flex-direction: column;
  padding: 0;
  width: 100%;
  height: auto;
  // max-height: 700rpx;
  background-color: #ffffff;
  z-index: 20;
  overflow: visible;
}

.popup-bottom {
  background: #ffffff;
  border-bottom: 1rpx solid $uni-line-color;
  display: flex;
  justify-content: center;
  padding: 20rpx;
  z-index: 10;
}

// 列表序号
.list-index-view {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  font-family: $uni-font-family;
  font-weight: $uni-font-weight-level1;
  font-size: $uni-font-size-level4;
  color: $uni-text-color-hint;
  line-height: 32rpx;
  text-align: left;
  font-style: normal;
  width: 80%;
}

.empty-view {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.empty-text {
  font-size: 28rpx;
  color: #888888;
}

.scroll-style {
  height: auto;
  // max-height: 700rpx;
  overflow: visible;
  position: relative
}

.scroll-item-view {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  align-items: center;
  //margin-top: 16rpx;
  row-gap: 8rpx;
  position: relative;
  height: auto;
  // max-height: 700rpx;
}

.detail-view {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.white-view {
  background: $uni-bg-color-inverse;
}

.gray-view {
  background: $uni-bg-color;
}
</style>
